package com.example.juc.demo;

import java.util.concurrent.*;

public class CompletableFutureDemo {

    public static void main(String[] args) {

        ExecutorService pool = Executors.newFixedThreadPool(3);

        long start = System.currentTimeMillis();

        //普通方法用时 6026
        /*for (int i = 0; i < 3; i++) {
            NetMall.getPrice();
        }*/

        try {
            CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {
                return NetMall.getPrice();

            }, pool);
            future.whenComplete((v, e) -> {
                System.out.println(Thread.currentThread().getName() + "价格为:" + v);
                System.out.println(Thread.currentThread().getName() + "完成任务！");
                long end = System.currentTimeMillis();
                System.out.println("处理结束，总计处理时长：" + (end - start));
            }).exceptionally(e -> {
                System.out.println("有异常：" + e.getMessage());
                return null;
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            pool.shutdown();
        }

        //runAsync无返回值 .join会阻塞线程
        CompletableFuture.runAsync(()->{
            System.out.println(Thread.currentThread().getName() + "开始执行任务！");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "完成任务！");
        });


        System.out.println("主线程正在干其他的");

    }

    public static String format(String name, Double price) {
        return String.format("mysql在 %s 中的价格为 %.2f", name, price);
    }


}

class NetMall {


    public static Double getPrice() {
        System.out.println(Thread.currentThread().getName() + "正在处理中");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return ThreadLocalRandom.current().nextDouble();
    }

}